package com.skyun.watchmanager.wear;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.skyun.watchserer.common.models.AppInfo;
import com.skyun.watchserer.common.models.Const;
import com.skyun.watchserer.common.models.DeviceInfo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import me.skyun.androidarch.common.Utils;
import me.skyun.androidarch.connect.BluetoothClient;
import me.skyun.androidarch.connect.BluetoothServer;
import me.skyun.androidarch.connect.Connection;
import me.skyun.androidarch.connect.Server;
import me.skyun.androidarch.connect.TcpClient;

public class ConnActivity extends Activity {

    private TextView mConnectionView;
    private EditText mMsgEditor;
    private TextView mLogView;
    private Connection mConnection;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Inflate the layout for this fragment
        setContentView(R.layout.activity_main);
        setTitle(getClass().getSimpleName());
        mConnectionView = (TextView) findViewById(R.id.main_text);
        //text field for output info.
//        mConnectionView = (TextView) findViewById(R.id.server_tv_connection);
//        mMsgEditor = (EditText) findViewById(R.id.server_et_msg);
//        mLogView = (TextView) findViewById(R.id.server_tv_log);

        if (checkEmulator()) {
            startTcpConnect();
        } else {
            startBluetoothListen();
        }
    }

    private static String getSystemProperty(String name) throws Exception {
        Class systemPropertyClazz = Class.forName("android.os.SystemProperties");
        return (String) systemPropertyClazz.getMethod("get", new Class[]{String.class})
                .invoke(systemPropertyClazz, new Object[]{name});
    }

    public static boolean checkEmulator() {
        try {
            boolean goldfish = getSystemProperty("ro.hardware").contains("goldfish");
            boolean emu = getSystemProperty("ro.kernel.qemu").length() > 0;
            boolean sdk = getSystemProperty("ro.product.model").equals("sdk");
            if (emu || goldfish || sdk) {
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }

    private void startTcpConnect() {
        new TcpClient("10.0.2.2", 5602, new ConnectionCallback()).startRun();
    }

    private void startBluetoothListen() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (!adapter.isEnabled()) {
            adapter.enable();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        new BluetoothServer(Const.BLUETOOTH_NAME, Const.BLUETOOTH_UUID, mServerCallback, new ConnectionCallback()).startListen();
    }

    @Override
    protected void onDestroy() {
        if (mConnection != null) {
            mConnection.disconnect();
        }
        super.onDestroy();
    }

    public void logMsg(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                mLogView.append(str + "\n");
            }
        });
    }

    public void onDisconnectClick(View v) {
        Connection connection = (Connection) mConnectionView.getTag();
        if (connection != null) {
            connection.disconnect();
        }
    }

    private static DeviceInfo getDeviceInfo(Context context) {
        DeviceInfo info = new DeviceInfo();
        info.brand = Build.BRAND;
        info.model = Build.MODEL;
        info.releaseVersion = Build.VERSION.RELEASE;
        info.romTotalSize = Utils.getRomTotalSize(context);
        info.sdTotalSize = Utils.getSDTotalSize(context);
        return info;
    }

    private Server.Callback mServerCallback = new Server.DefaultCallback() {
        @Override
        public void onListenStarted() {
            mConnectionView.setText("[监听连接中...]");
        }
    };

    private class ConnectionCallback extends Connection.DefaultCallback {

        @Override
        public void onStateChanged(Connection connection, Connection.State state) {
            if (state == Connection.State.Connected) {
                mConnectionView.setText(connection.getRemoteName());
                mConnectionView.setBackgroundColor(Color.GREEN);
                mConnectionView.setTag(connection);
                mConnection = connection;
            } else if (state == Connection.State.Connecting) {
                mConnectionView.setBackgroundColor(Color.YELLOW);
                mConnectionView.setTag(connection);
            } else if (state == Connection.State.Disconnected) {
                mConnectionView.setText(null);
                mConnectionView.setBackgroundColor(Color.RED);
                mConnection = null;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        new TcpClient("10.0.2.2", 5602, new ConnectionCallback()).startRun();
                    }
                }, 2000);
            }
        }

        @Override
        public void onReceive(final Connection connection, String msg, String arg) {
            if ("app".equals(msg)) {
                DeviceInfo deviceInfo = getDeviceInfo(getApplicationContext());
                connection.sendObject(deviceInfo);

                List<String> resolveInfos = Utils.getWatchFaceNames(getApplicationContext());
                connection.sendList(resolveInfos);

//                if (true)
//                    return;

                PackageManager pm = getPackageManager();
                List<ApplicationInfo> applicationInfos = Utils.getApps(ConnActivity.this);
                final List<AppInfo> appInfos = new ArrayList<>(applicationInfos.size());
                for (ApplicationInfo applicationInfo : applicationInfos) {
                    AppInfo info = new AppInfo();
                    info.name = applicationInfo.loadLabel(pm).toString();
                    info.packageName = applicationInfo.packageName;

                    PackageInfo packageInfo = Utils.getAppPackageInfo(getApplicationContext(), applicationInfo.packageName);
                    info.version = packageInfo.versionName;
                    info.installTime = packageInfo.firstInstallTime;
                    info.updateTime = packageInfo.lastUpdateTime;

                    appInfos.add(info);
                }
                connection.sendList(appInfos);
            } else if ("app_icon".equals(msg)) {
                List<String> packNames = new Gson().fromJson(arg, new TypeToken<List<String>>() {
                }.getType());
                List<ApplicationInfo> applicationInfos = Utils.getApps(ConnActivity.this);
                PackageManager pm = getPackageManager();
                for (ApplicationInfo applicationInfo : applicationInfos) {
                    if (packNames.contains(applicationInfo.packageName)) {
                        Drawable icon = applicationInfo.loadIcon(pm);
                        connection.sendDrawable(applicationInfo.packageName, icon);
                    }
                }
            } else if ("theme".equals(msg)) {
                Bitmap bitmap = screencap();
                connection.sendBitmap("theme", bitmap);
            } else if ("device_info".equals(msg)) {
                DeviceInfo info = getDeviceInfo(getApplicationContext());
                connection.sendObject(info);
            }
        }

        @Override
        public void onLog(String log) {
            logMsg(log);
        }

        private Bitmap screencap() {
            //1.构建Bitmap
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            int w = display.getWidth();
            int h = display.getHeight();

            Bitmap bitmap;

            //2.获取屏幕
            View decorview = getWindow().getDecorView();
            decorview.setDrawingCacheEnabled(true);
            bitmap = decorview.getDrawingCache();
            return bitmap;
        }
    }
}
